package com.cubeofnine.sugar.activity.import_contact;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TableLayout.LayoutParams;

import com.cubeofnine.sugar.ActivityImpt;
import com.cubeofnine.sugar.ContentDetailActivity;
import com.cubeofnine.sugar.R;
import com.cubeofnine.sugar.business.BusinessImpt;
import com.cubeofnine.sugar.service.element.Contact;
import com.cubeofnine.sugar.service.element.ReturnExportContactList;
import com.cubeofnine.utils.ActivityParams;
import com.cubeofnine.utils.ScrollingTextView;

public class ImportContactsListActivity extends ActivityImpt {
	private TextView headerText = null;
	private List<Contact> contacts = new Vector<Contact>();

	public String getClassName() {
		return ImportContactsListActivity.class.getName();
	}

	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClassName(), "onCreate() : Start");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_contacts);

		headerText = (TextView) findViewById(R.id.header_title);

		initProgressDialog(null);
		Thread thread = new ImportContactsListThread(this);
		thread.start();

		Log.i(getClassName(), "onCreate() : End");
	}

	public void onStart() {
		Log.i(getClassName(), "onStart() : Start");

		super.onStart();

		headerText.setText(R.string.function_import_contacts);

		Thread thread = (Thread) getLastNonConfigurationInstance();
		if (thread != null && thread.isAlive()) {
			initProgressDialog(null);
		}

		Log.i(getClassName(), "onStart() : End");
	}

	public void onDestroy() {
		Log.i(getClassName(), "onDestroy() : Start");

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		Log.i(getClassName(), "onDestroy() : End");
		super.onDestroy();
	}

	public void onBackPressed() {
		Log.i(getClassName(), "onBackPressed() : Start");

		Thread thread = (Thread) getLastNonConfigurationInstance();
		if (thread == null || !thread.isAlive()) {
			super.onBackPressed();
		}

		Log.i(getClassName(), "onBackPressed() : End");
	}

	public void initialProcess(ReturnExportContactList result, String message) {
		Log.i(getClassName(), "initialProcess() : Start");

		try {
			if (message == null || message.isEmpty()) {
				if (result != null) {
					if (result.getError().getNumber() == 0) {
						List<Contact> contacts = result.getContacts();
						Log.d(getClassName(),
								"contactCount = " + contacts.size());

						if (contacts != null && !contacts.isEmpty()) {
							LinearLayout root = (LinearLayout) findViewById(R.id.body_root_linear_layout);
							root.removeAllViewsInLayout();

							Iterator<Contact> contactIter = null;
							Contact contact = null;

							String id = null;
							String displayName = null;
							String companyName = null;
							String jobTitle = null;

							// List<Phone> phones = null;
							// Iterator<Phone> phoneIter = null;
							// Phone phone = null;
							// String phoneNumber = null;
							// String phoneType = null;
							//
							// List<Email> emails = null;
							// Iterator<Email> emailIter = null;
							// Email email = null;
							// String emailAddress = null;
							// String emailType = null;
							//
							// List<Address> addresses = null;
							// Iterator<Address> addressIter = null;
							// Address address = null;
							// String addressType = null;
							// String street = null;
							// String city = null;
							// String state = null;
							// String postalcode = null;
							// String country = null;

							LinearLayout contactLayout = null;
							LinearLayout textGroupLayout = null;
							ScrollingTextView textView = null;
							CheckBox checkBox = null;

							// Contact Root Layout
							LinearLayout.LayoutParams contactLayoutParams = new LinearLayout.LayoutParams(
									LayoutParams.MATCH_PARENT,
									LayoutParams.WRAP_CONTENT);// W,H
							contactLayoutParams.setMargins(10, 2, 10, 2);// left,
																			// top,
																			// right,
																			// bottom
							LinearLayout.LayoutParams textGroupLayoutParams = new LinearLayout.LayoutParams(
									LayoutParams.MATCH_PARENT,
									LayoutParams.WRAP_CONTENT);// W,H
							textGroupLayoutParams.setMargins(5, 0, 0, 0);// left,
																			// top,
																			// right,
																			// bottom

							LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
									LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT);
							// textViewParams.setMargins(0, 2, 0, 2);

							this.contacts = contacts;

							int index = 0;
							contactIter = contacts.iterator();
							while (contactIter.hasNext()) {
								contact = contactIter.next();

								// initial variable
								{
									id = contact.getId();
									displayName = "";

									if (contact.getFirst_name() != null
											&& !contact.getFirst_name()
													.isEmpty()) {
										displayName = contact.getFirst_name();
									}

									if (contact.getLast_name() != null
											&& !contact.getLast_name()
													.isEmpty()) {
										displayName += " "
												+ contact.getLast_name();
									}

									displayName = displayName.trim();

									companyName = contact.getCompany_name();
									jobTitle = contact.getJob_title();
								}

								// Create Group Contact
								contactLayout = new LinearLayout(this);
								contactLayout
										.setLayoutParams(contactLayoutParams);
								contactLayout
										.setOrientation(LinearLayout.HORIZONTAL);

								// Check Box
								checkBox = new CheckBox(this);
								checkBox.setId(index++);
								checkBox.setOnClickListener(new OnClickCheckSame(
										this));
								contactLayout.addView(checkBox);

								// Text Layout
								textGroupLayout = new LinearLayout(this);
								textGroupLayout
										.setLayoutParams(textGroupLayoutParams);
								textGroupLayout
										.setOrientation(LinearLayout.VERTICAL);
								textGroupLayout.setGravity(Gravity.CENTER);

								{
									// Contact Name
									textView = new ScrollingTextView(this);
									textView.setLayoutParams(textViewParams);
									textView.setText(displayName);
									textView.setTextColor(Color
											.rgb(0, 102, 255));// Blue
									textView.setTextAppearance(this,
											android.R.attr.textAppearanceLarge);
									textView.setSingleLine(true);
									textView.setHorizontallyScrolling(true);
									textView.setEllipsize(TruncateAt.MARQUEE);
									textView.setMarqueeRepeatLimit(1);
									textView.setMovementMethod(new ScrollingMovementMethod());

									textView.setOnClickListener(new OnClickViewPhoneContactDetail(
											this, id));

									textGroupLayout.addView(textView);

									// JobTitle Title
									if (jobTitle == null || jobTitle.isEmpty()) {
										jobTitle = "";
									}

									textView = new ScrollingTextView(this);
									textView.setLayoutParams(textViewParams);
									textView.setText("Job Title : " + jobTitle);
									textView.setTextColor(Color.rgb(170, 170,
											170));// Gray
									textView.setTextAppearance(this,
											android.R.attr.textAppearanceSmall);
									textView.setSingleLine(true);
									textView.setHorizontallyScrolling(true);
									textView.setEllipsize(TruncateAt.MARQUEE);
									textView.setMarqueeRepeatLimit(1);
									textView.setMovementMethod(new ScrollingMovementMethod());
									textGroupLayout.addView(textView);

									// Company
									if (companyName != null
											&& !companyName.isEmpty()) {
										textView = new ScrollingTextView(this);
										textView.setLayoutParams(textViewParams);
										textView.setText("Company : "
												+ companyName);
										textView.setTextColor(Color.rgb(170,
												170, 170));// Gray
										textView.setTextAppearance(
												this,
												android.R.attr.textAppearanceSmall);
										textView.setSingleLine(true);
										textView.setHorizontallyScrolling(true);
										textView.setEllipsize(TruncateAt.MARQUEE);
										textView.setMarqueeRepeatLimit(1);
										textView.setMovementMethod(new ScrollingMovementMethod());
										textGroupLayout.addView(textView);
									}
								}

								contactLayout.addView(textGroupLayout);
								root.addView(contactLayout);
							}
						}
					} else {
						message = result.getError().getDescription();
						alertDialog(message);
					}
				} else {
					alertDialog("No Data Found.");
				}
			} else {
				alertDialog(message);
			}

			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
				dialog = null;
			}
		} catch (Exception e) {
			Log.e(getClassName(), "Error", e);
		}

		Log.i(getClassName(), "initialProcess() : End");
	}

	public void onClickCheckAll(View view) {
		Log.i(getClassName(), "onClickCheckAll() : Start");

		if (this.contacts != null && !this.contacts.isEmpty()) {
			CheckBox checkBox = (CheckBox) view;
			boolean checked = checkBox.isChecked();

			for (int i = 0; i < this.contacts.size(); i++) {
				checkBox = (CheckBox) findViewById(i);
				checkBox.setChecked(checked);
			}
		}

		Log.i(getClassName(), "onClickCheckAll() : End");
	}

	public void onClickCheckSame(View view) {
		Log.i(getClassName(), "onClickCheckSame() : Start");

		if (this.contacts != null && !this.contacts.isEmpty()) {
			CheckBox checkBox = null;
			boolean checked = true;
			for (int i = 0; i < this.contacts.size(); i++) {
				checkBox = (CheckBox) findViewById(i);
				if (!checkBox.isChecked()) {
					checked = false;
					break;
				}
			}

			checkBox = (CheckBox) findViewById(R.id.check_all);
			checkBox.setChecked(checked);
		}

		Log.i(getClassName(), "onClickCheckSame() : End");
	}

	public void onClickSync(View view) {
		Log.i(getClassName(), "onClickSync() : Start");
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));

		if (this.contacts != null && !this.contacts.isEmpty()) {
			List<Contact> selectedItem = new Vector<Contact>();

			CheckBox checkBox = null;
			Contact contact = null;
			for (int i = 0; i < this.contacts.size(); i++) {
				checkBox = (CheckBox) findViewById(i);
				if (checkBox.isChecked()) {
					contact = contacts.get(i);
					selectedItem.add(contact);
				}
			}

			if (selectedItem.isEmpty()) {
				alertDialog("Please select at least one item.");
			} else {
				AlertDialog.Builder adb = new AlertDialog.Builder(this);

				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.setTitle(R.string.function_import_contacts);
				adb.setMessage(R.string.msg_want_to_continue);
				adb.setPositiveButton(R.string.button_yes,
						new OnClickDialogToContinue(this, selectedItem, true));
				adb.setNegativeButton(R.string.button_no,
						new OnClickDialogToContinue(this, selectedItem, false));
				adb.show();
			}
		} else {
			alertDialog("Please select at least one item.");
		}

		Log.i(getClassName(), "onClickSync() : End");
	}

	public void gotoNextProcess(List<Contact> selectedItem, boolean answer) {
		Log.i(getClassName(), "gotoNextProcess() : Start");
		Log.d(getClassName(), "answer = " + answer);

		if (answer) {
			initProgressDialog(null);

			Thread thread = (Thread) getLastNonConfigurationInstance();
			if (thread == null || !thread.isAlive()) {
				thread = new SyncDownContactsListThread(this, selectedItem);
				thread.start();
			}
		}

		Log.i(getClassName(), "gotoNextProcess() : End");
	}

	public void resultSyncProcess(int totalCount, int insertCount,
			String errorMessage) {
		Log.i(getClassName(), "resultSyncProcess() : String");
		Log.d(getClassName(), "totalCount = " + totalCount);
		Log.d(getClassName(), "insertCount = " + insertCount);
		Log.d(getClassName(), "errorMessage = " + errorMessage);

		if (errorMessage != null && !"".equals(errorMessage.trim())) {
			alertDialog(errorMessage);
		} else {
			String message = "Selected Items : " + totalCount + "\n"//
					+ "Success Items : " + insertCount + "\n" //
					+ "Duplicate/Fail Items : " + (totalCount - insertCount);

			AlertDialog.Builder adb = new AlertDialog.Builder(this);

			adb.setIcon(android.R.drawable.ic_dialog_alert);
			adb.setTitle(R.string.function_import_contacts);
			adb.setMessage(message);
			adb.setPositiveButton(R.string.button_ok, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			});
			adb.show();
		}

		dialog.dismiss();
		Log.i(getClassName(), "resultSyncProcess() : End");
	}

	public void gotoPhoneContactDetail(View view, String id) {
		Log.i(getClassName(), "gotoPhoneContactDetail() : Start");
		view.startAnimation(AnimationUtils.loadAnimation(this,
				R.anim.image_click));

		List<ActivityParams> params = new Vector<ActivityParams>();
		params.add(new ActivityParams(ContentDetailActivity.MODULE_ID, id));
		params.add(new ActivityParams(ContentDetailActivity.MODULE_NAME,
				BusinessImpt.MODULE_CONTACTS));

		gotoActivity(ContentDetailActivity.class, params);

		Log.i(getClassName(), "gotoPhoneContactDetail() : End");
	}

	public void onClickHomeButton(View view) {
		try {
			view.startAnimation(AnimationUtils.loadAnimation(this,
					R.anim.image_click));
			createMenuPopup(R.string.label_home_menu, new String[] {
					MENU_EXPORT_CONTACT, MENU_LOGOUT });
		} catch (Exception e) {
			Log.e(ActivityImpt.class.getName(), "Error", e);
		}
	}
}
